<template>
  <Form class="xtx-form" ref="formCom" :validation-schema="mySchema" v-slot="{errors}" autocomplete="off">
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field class="input" :class="{err:errors.account}" type="text" placeholder="请输入用户名" v-model="form.account" name="account"/>
      </div>
      <div :class="{error:errors.account}">{{errors.account}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field class="input" :class="{err:errors.mobile}" type="text" placeholder="请输入手机号" v-model="form.mobile" name="mobile"/>
      </div>
      <div :class="{error:errors.mobile}">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field class="input" :class="{err:errors.code}" type="text" placeholder="请输入验证码" v-model="form.code" name="code"/>
        <span class="code" @click="send">{{time===0?'发送验证码':`${time}秒后发送`}}</span>
      </div>
      <div :class="{error:errors.code}">{{errors.code}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field class="input" :class="{err:errors.password}" type="password" placeholder="请输入密码" v-model="form.password" name="password"/>
      </div>
      <div :class="{error:errors.password}">{{errors.password}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field class="input" :class="{err:errors.rePassword}" type="password" placeholder="请确认密码" v-model="form.rePassword" name="rePassword"/>
      </div>
      <div :class="{error:errors.rePassword}">{{errors.rePassword}}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit">立即提交</a>
  </Form>
</template>

<script>
import { Form, Field } from 'vee-validate'
import { reactive, ref, onUnmounted } from 'vue'
import schema from '@/utils/vee-validate-schema'
import { userQQPatchCode, userQQPatchLogin } from '@/api/user'
import Message from '@/components/library/Message'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
export default {
  name: 'CallbackPatch',
  components: { Form, Field },
  props: {
    // 第3方标识
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    // 表单数据对象
    const form = reactive({
      account: null,
      mobile: null,
      code: null,
      password: null,
      rePassword: null
    })
    // 校验规则对象
    const mySchema = {
      account: schema.accountApi,
      mobile: schema.mobile,
      code: schema.code,
      password: schema.password,
      rePassword: schema.rePassword
    }

    // 请求发送验证码
    const time = ref(0)
    const formCom = ref(null)
    let timer = null
    const send = async () => {
      // 校验通过则返回true，否则返回错误文本
      const valid = mySchema.mobile(form.mobile)
      if (valid === true) {
        if (time.value === 0) {
          await userQQPatchCode(form.mobile)
          // 弹成功提示
          Message({ type: 'success', text: '发送成功' })
          // 倒计时60秒
          time.value = 60
          clearInterval(timer)
          timer = setInterval(() => {
            time.value--
            if (time.value <= 0) {
              clearInterval(timer)
            }
          }, 1000)
        }
      } else {
        // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
        formCom.value.setFieldError('mobile', valid)
      }
    }
    // 组件销毁清除倒计时
    onUnmounted(() => {
      clearInterval(timer)
      // 重置表单校验规则
      // formCom.value.resetForm()
    })

    // 提交完善信息函数
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const submit = async () => {
      // 表单验证通过发请求
      const valid = await formCom.value.validate()
      if (valid) {
        // 利用try...catch捕捉错误
        try {
          const data = await userQQPatchLogin({ unionId: props.unionId, mobile: form.mobile, code: form.code, account: form.account, password: form.password })
          // 保存请求回来的用户信息在vuex
          const { id, account, avatar, mobile, nickname, token } = data.result
          store.commit('user/setUser', { id, account, avatar, mobile, nickname, token })
          // 需要先合并完购物车
          store.dispatch('cart/mergeCart').then(() => {
            // 如果是其他跳转过来的，需要跳转回去
            router.push(store.state.user.redirectUrl || '/')
            // 成功消息提示
            Message({ type: 'success', text: '登录成功' })
          })
        } catch (error) {
          // 当请求失败，捕捉失败信息并且提示
          Message({ type: 'error', text: error.response.data.message || '用户信息错误' })
        }
      } else {
        Message({ type: 'error', text: '请正确填写信息' })
      }
    }
    return { form, mySchema, formCom, send, time, submit }
  }
}
</script>

<style scoped lang='less'>
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
